﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.ComponentModel;

namespace WpfSample
{
    class AnswerViewModel : INotifyPropertyChanged
    {
        public AsyncCommand<string, int> UltimateAnswerCommand { get; private set; }

        private string _answer;
        public string Answer
        {
            get { return _answer; }
            set 
            {
                _answer = value;
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Answer"));    
            }
        }

        public AnswerViewModel()
        {
            UltimateAnswerCommand = new AsyncCommand<string, int>(GetAnswer);
            UltimateAnswerCommand.Completed += new AsyncFuncCompletedEventHandler<int>(GetUltimateAnswer_Completed);
        }

        void GetUltimateAnswer_Completed(object sender, AsyncFuncCompletedEventArgs<int> e)
        {
            if (e.Error != null)
            {
            }
            else if (e.Cancelled)
            {
            }
            else
            {
                Answer = e.Result.ToString();
            }
        }

        private int GetAnswer(string question, Func<bool> isCancelled,  Action<int> reportProgress)
        {
            for (int i = 1; i <= 10; i++)
            {
                if (isCancelled()) return 0;
                System.Threading.Thread.Sleep(500);
                reportProgress(i*10);
            }
            return 42;
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
